<?php

namespace app\components;

use app\models\Sms;
use app\models\User;
use app\utils\SettingUtils;
use yii;
use yii\web\View;

class WebController extends BaseController {

    public $layout = 'main';

    public $keywords;
    public $description;

    protected $modelClass;

    /**
     * @var User
     */
    public $user;

    public function init() {
        parent::init();
        $this->user = Yii::$app->user->identity;
    }

    public function beforeAction($action) {
        $this->user = Yii::$app->user->identity;
        $this->view->title = SettingUtils::get('seo_title');

        if (!$this->isAjax()) {
            if (Yii::$app->user->isGuest) {
                $loginUrl = yii\helpers\Url::to(['auth/login', 'ref' => Yii::$app->request->getUrl()]);
                $this->view->registerJs("window.loginUrl = '{$loginUrl}';", View::POS_HEAD);
                $this->view->registerJs("window.user = {};", View::POS_HEAD);
            } else {
                $user = yii\helpers\Json::encode($this->user->toArray(['type', 'uname', 'avatar']));
                $this->view->registerJs("window.user = {$user};", View::POS_HEAD);
            }

            $this->getLikeId();
        }

        return parent::beforeAction($action);
    }

    public function getUserId() {
        return $this->user ? $this->user->id : NULL;
    }

    protected function show_success($msg, $url = '', $time = 3) {
        return $this->show('success', $msg, $url, $time);
    }

    protected function show_error($msg, $url = '', $time = 3) {
        return $this->show('error', $msg, $url, $time);
    }

    protected function show($type, $msg, $url, $time) {
        return $this->render(compact('msg', 'url', 'time'), "/common/{$type}");
    }

    public function actionError(\Exception $exception) {
        if ($exception instanceof yii\web\HttpException) {
            $this->view->title = '页面不存在!';
            return $this->show('404', $exception->getMessage(), '', 3);
        }

        $this->view->title = '系统异常';
        return $this->show_error($exception->getMessage());
    }

    public function actionVerify() {
        $phone = $this->getParam('phone');
        $sms = new Sms();
        return $sms->send($phone);
    }

    public function afterAction($action, $result) {
        $result = parent::afterAction($action, $result);
        $ref = $this->get('ref');
        if (is_array($result) && isset($result['data']) && NULL !== $ref) {
            $result['redirect'] = $ref;
        }
        return $result;
    }

    public function getLikeId() {
        $likeId = '__like';
        $value = $this->getCookie($likeId);
        if (!$value) {
            $value = time();
            $this->sendCookie($likeId, $value, 86400 * 365 * 5);
        }
        return $value;
    }
}